package com.duoduo.剑指Offer;

import com.duoduo.ListNode;

import java.util.ArrayList;
import java.util.Stack;

/**
 * @program: algorithm
 * @description: 从尾到头打印链表03
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 * 示例 1：
 * <p>
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 * @author: chaidl  ！
 * @create: 2022-05-21 23:41
 */
public class 从尾到头打印链表03 {
	public int[] reversePrint(ListNode head) {
		if (head == null) {
			return new int[0];
		}
		ListNode tmp = head;
		Stack<ListNode> stack = new Stack<>();
		
		while (tmp != null) {
			stack.push(tmp);
			tmp = tmp.next;
		}
		int size = stack.size();
		int[] result = new int[size];
		for (int i = 0; i < size; i++) {
			result[i] = stack.pop().val;
		}
		return result;
	}
	ArrayList<Integer> tmp = new ArrayList<Integer>();
	//递归
	public int[] reversePrint2(ListNode head) {
		recur(head);
		int[] reult=new int[tmp.size()];
		for (int i = 0; i < tmp.size(); i++) {
			reult[i]=tmp.get(i);
		}
		return reult;
	}
	
	private void recur(ListNode head) {
		//递归出口
		if (head==null){
			return;
		}
		recur(head.next);
		tmp.add(head.val);
	}
}
